package com.lk.pet.customers.controller;

import com.lk.pet.customers.exception.ResourceNotFoundException;
import com.lk.pet.customers.model.Owner;
import com.lk.pet.customers.service.OwnerService;
import io.micrometer.core.annotation.Timed;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.Min;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/owners")
@Timed("petclinic.owner")
@Slf4j
public class OwnerController {

    private final OwnerService ownerService;

    public OwnerController(OwnerService ownerService) {
        this.ownerService = ownerService;
    }

    @GetMapping
    public List<Owner> findAll(){
        return ownerService.findAll();
    }

    @GetMapping("/{ownerId}")
    public Optional<Owner> findOwner(@PathVariable("ownerId") @Min(1) Integer id){
        return ownerService.findById(id);
    }

    @RequestMapping("/remove/{id}")
    public String remove(@PathVariable("id") Integer id){
        ownerService.removeById(id);
        return "remove ok!";
    }

    // update owner

    @PutMapping(value = "/{ownerId}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void updateOwner(@PathVariable("ownerId") @Min(1) Integer ownerId, @Valid @RequestBody Owner ownerRequest){
        final Optional<Owner> owner = ownerService.findById(ownerId); //查找传来的用户
        final Owner ownerModel  = owner.orElseThrow(() -> new ResourceNotFoundException("owner" + ownerId + "not found"));

        ownerModel.setFirstName(ownerRequest.getFirstName());
        ownerModel.setLastName(ownerRequest.getLastName());
        ownerModel.setCity(ownerRequest.getCity());
        ownerModel.setAddress(ownerRequest.getAddress());
        ownerModel.setTelephone(ownerRequest.getTelephone());
        ownerService.save(ownerModel);
    }
}
